package com.gitee.fastmybatis.core.ext;

import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.Collection;
import java.util.Optional;

/**
 * @author thc
 */
public class SqlSessionFactoryBuilderContext {

    private final SqlSessionFactoryBuilderExt sqlSessionFactoryBuilderExt;

    private final Configuration configuration;

    private SqlSessionFactory sqlSessionFactory;


    public SqlSessionFactoryBuilderContext(SqlSessionFactoryBuilderExt sqlSessionFactoryBuilderExt, Configuration configuration) {
        this.sqlSessionFactoryBuilderExt = sqlSessionFactoryBuilderExt;
        this.configuration = configuration;
    }

    public SqlSessionFactory getSqlSessionFactory() {
        if (this.sqlSessionFactory == null) {
            sqlSessionFactory = this.sqlSessionFactoryBuilderExt.build(configuration);
            String envId = Optional.ofNullable(configuration.getEnvironment()).map(Environment::getId).orElse("default");
            ExtContext.addSqlSessionFactory(envId, sqlSessionFactory);
            Collection<Class<?>> mapperClasses = ExtContext.listMapperClass();
            for (Class<?> mapperClass : mapperClasses) {
                ExtContext.addSqlSessionFactory(mapperClass, sqlSessionFactory);
            }
        }
        return sqlSessionFactory;
    }

    public SqlSessionFactoryBuilderExt getSqlSessionFactoryBuilderExt() {
        return sqlSessionFactoryBuilderExt;
    }

    public Configuration getConfiguration() {
        return configuration;
    }

}
